package com.iteaj.plugin.event;

import com.alipay.sofa.ark.api.ArkClient;
import com.alipay.sofa.ark.loader.JarBizArchive;
import com.alipay.sofa.ark.loader.archive.JarFileArchive;
import com.alipay.sofa.ark.spi.archive.Archive;
import com.alipay.sofa.ark.spi.archive.BizArchive;
import com.alipay.sofa.ark.spi.event.AfterFinishStartupEvent;
import com.alipay.sofa.ark.spi.event.plugin.BeforePluginStartupEvent;
import com.alipay.sofa.ark.spi.service.event.EventHandler;
import com.iteaj.plugin.IzoneConfig;
import com.iteaj.plugin.spi.Consts;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static com.alipay.sofa.ark.spi.constant.Constants.ARK_BIZ_MARK_ENTRY;

/**
 * create time: 2020/3/2
 *  ark启动完成之后, 启动biz目录下的biz应用
 * @author iteaj
 * @since 1.0
 */
public class StartLibBizWithFinishStartup implements EventHandler<AfterFinishStartupEvent> {

    private static File[] bizFiles = new File[]{};

    static {
        File rootDir = IzoneConfig.getRootDir();
        if(rootDir != null) {
            File bizDir = new File(rootDir, Consts.BIZ_DIR);
            if(bizDir.exists() && bizDir.isDirectory()) {
                bizFiles = bizDir.listFiles(pathname -> {
                    if (!pathname.getPath().endsWith(Consts.JAR_SUFFIX)) {
                        return false;
                    }
                    try {
                        JarFileArchive archive = new JarFileArchive(pathname);
                        JarBizArchive bizArchive = new JarBizArchive(archive);
                        return bizArchive.isEntryExist(entry -> entry.getName().equals(ARK_BIZ_MARK_ENTRY));
                    } catch (IOException e) {
                        return false;
                    }
                });
            }
        }
    }

    @Override
    public int getPriority() {
        return LOWEST_PRECEDENCE;
    }

    @Override
    public void handleEvent(AfterFinishStartupEvent event) {
        Arrays.asList(bizFiles).forEach(file -> {
            try {
                ArkClient.installBiz(file);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }
}
